import random
from flask import Blueprint, g, render_template, session, current_app

from .database import db
from .auth import login_required
from .crud import Courses, Users, Timetables

from .router import to_route
bp = Blueprint('student', __name__, url_prefix='/student')

@bp.before_app_request
def load_logged_in_user():
    user_id = session.get('user_id')
    if user_id is None:
        g.user = None
    else:
        g.user = Users.get_user(db.session, user_id)

@bp.route('/grade')
@login_required
def grade():
    courses = Courses.get_courses(db.session, g.user.id)
    timetables = Timetables.get_timetables(db.session, g.user.id)
    context = {
        'user': g.user,
        'courses': courses,
        'timetables': timetables,
        'randrange': random.randrange
    }
    return to_route('student/grade.html', **context)

@bp.route('/social')
@login_required
def social():
    users = Users.get_users(db.session)
    random.shuffle(users)

    friends = []
    for user in users:
        friends.append(user)
        if len(friends) >= 3:
            break

    teachers = []
    for user in users:
        if user.role.name != 'professor':
            continue
        teachers.append(user)
        if len(teachers) >= 3:
            break

    context = {
        'user': g.user,
        'friends': friends,
        'teachers': teachers,
        'school': current_app.config.get('SCHOOL_NAME')
    }
    return to_route('student/social.html', **context)

@bp.route('/course')
@login_required
def course():
    courses = Courses.get_courses(db.session, g.user.id)
    timetables = Timetables.get_timetables(db.session, g.user.id)
    context = {
        'user': g.user,
        'courses': courses,
        'timetables': timetables,
        'school': current_app.config.get('SCHOOL_NAME')
    }
    return to_route('student/course.html', **context)

@bp.route('/timetable')
@login_required
def timetable():
    timetables = Timetables.get_timetables_of_week(db.session, g.user.id)
    context = {
        'user': g.user,
        'timetables': timetables,
        'school': current_app.config.get('SCHOOL_NAME')
    }
    return to_route('student/timetable.html', **context)